package com.sbm.shiro;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import com.sbm.domain.model.PermissionModel;
import com.sbm.domain.model.RoleModel;
import com.sbm.domain.model.UserModel;
import com.sbm.svc.UserService;

public class ShiroRealm extends AuthorizingRealm {

	@Autowired
	private UserService userService;

	public ShiroRealm() {
		this.setName(this.getClass().getSimpleName());
	}

	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		System.out.println("————Shiro权限认证————");
		SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
		UserModel user = (UserModel) principals.getPrimaryPrincipal();
		if (user != null) {
			for (RoleModel role : user.getRoleList()) {
				authorizationInfo.addRole(role.getName());
				for (PermissionModel permission : role.getPermissionList()) {
					authorizationInfo.addStringPermission(permission.getName());
				}
			}
			return authorizationInfo;
		}
		return null;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken autheToken)
			throws AuthenticationException {
		System.out.println("————Shiro登录认证————");
		UsernamePasswordToken token = (UsernamePasswordToken) autheToken;
		System.out.println("账号：" + token.getUsername());
		System.out.println("密码：" + new String(token.getPassword()));
		System.out.println("令牌：" + token.getCredentials().toString());
		System.out.println("主机：" + token.getHost());
		UserModel user = this.userService.login(token.getUsername());
		if (user == null)
			return null;
		// 密文
		// SimpleAuthenticationInfo authenticationInfo = new
		// SimpleAuthenticationInfo(user, user.getPwd(),
		// ByteSource.Util.bytes("pwd"), this.getName());
		// 明文
		SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(user, user.getPwd(), this.getName());
		return authenticationInfo;
	}

}
